package com.ikun.kunpicturebackend.manager.upload;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.ikun.kunpicturebackend.config.CosClientConfig;
import com.ikun.kunpicturebackend.exception.BusinessException;
import com.ikun.kunpicturebackend.exception.ErrorCode;
import com.ikun.kunpicturebackend.model.dto.file.PictureUploadResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 图片上传模板类
 */
@Slf4j
public abstract class PictureUploadTemplate {

    @Resource
    private CosManager cosManager;

    @Resource
    private CosClientConfig cosClientConfig;

    /**
     * 上传图片模板方法，定义上传流程
     *
     * @param inputSource      输入源（支持本地文件或URL）
     * @param uploadPathPrefix 路径前缀
     * @return
     */
    public final PictureUploadResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 1.校验图片
        validPicture(inputSource);

        // 2.构造图片上传地址
        // 2.1 16位UUID
        String uuid = RandomUtil.randomString(16);
        // 2.2 获取原始文件名
        String originalFilename = getOriginFilename(inputSource);
        String suffix = StrUtil.blankToDefault(FileUtil.getSuffix(originalFilename), "webp");
        // 2.3 上传文件名：yyyy-MM-dd_uuid.文件后缀
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, suffix);
        // 2.4 上传路径：/前缀/yyyy-MM-dd_uuid.文件后缀
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);

        File file = null;
        try {
            // 3. 创建临时文件
            file = File.createTempFile(uploadPath, null);
            // 处理文件来源(本地/URL)
            processFile(inputSource, file);

            // 4. 上传图片
            PutObjectResult putObjectResult = cosManager.putObject(uploadPath, file);
            // 4.1 得到原图图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 4.2 得到每一个图片处理结果
            List<CIObject> objectList = putObjectResult.getCiUploadResult().getProcessResults().getObjectList();
            if (!objectList.isEmpty()) {
                CIObject compressedCiObject = objectList.get(0);
                CIObject thumbnailCiObject = compressedCiObject;
                if (objectList.size() > 1)
                    thumbnailCiObject = objectList.get(1);
                // 封装压缩图返回结果
                return buildResult(originalFilename, compressedCiObject, thumbnailCiObject, imageInfo);
            }
            // 封装原图返回结果
            return buildResult(originalFilename, uploadPath, file, imageInfo);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片上传失败");
        } finally {
            deleteTempFile(file);
        }
    }

    /**
     * 校验输入源（本地文件或URL）
     *
     * @param inputSource
     */
    protected abstract void validPicture(Object inputSource);

    /**
     * 获取输入源的原始文件名
     *
     * @param inputSource
     * @return
     */
    protected abstract String getOriginFilename(Object inputSource);

    /**
     * 处理输入源并生成本地临时文件
     *
     * @param inputSource
     * @param file
     */
    protected abstract void processFile(Object inputSource, File file) throws IOException;

    /**
     * 删除临时文件
     *
     * @param file
     */
    public void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        boolean result = file.delete();
        if (!result) {
            log.error("file delete error, filepath = {}", file.getAbsolutePath());
        }
    }

    /**
     * 封装原图信息
     *
     * @param originalFilename
     * @param uploadPath
     * @param file
     * @param imageInfo 原图图片信息
     * @return
     */
    private PictureUploadResult buildResult(String originalFilename, String uploadPath, File file, ImageInfo imageInfo) {
        // 5. 封装返回结果到PictureUploadResult
        PictureUploadResult uploadResult = new PictureUploadResult();
        // 5.1 计算图片picScale宽高比例：宽/高
        int width = imageInfo.getWidth();
        int height = imageInfo.getHeight();
        Double picScale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();
        // 5.3 封装结果
        uploadResult.setPicColor(imageInfo.getAve());
        uploadResult.setPicWidth(width);
        uploadResult.setPicHeight(height);
        uploadResult.setPicScale(picScale);
        uploadResult.setName(FileUtil.mainName(originalFilename));
        uploadResult.setPicFormat(imageInfo.getFormat());
        uploadResult.setPicSize(FileUtil.size(file));
        uploadResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        return uploadResult;
    }

    private PictureUploadResult buildResult(String originalFilename, CIObject compressedCiObject, CIObject thumbnailCiObject, ImageInfo imageInfo) {
        PictureUploadResult uploadResult = new PictureUploadResult();
        int width = compressedCiObject.getWidth();
        int height = compressedCiObject.getHeight();
        Double picScale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();
        // 获取图片主色调
        String picColor = imageInfo.getAve();
        uploadResult.setPicColor(picColor);
        uploadResult.setPicWidth(width);
        uploadResult.setPicHeight(height);
        uploadResult.setPicScale(picScale);
        uploadResult.setName(FileUtil.mainName(originalFilename));
        uploadResult.setPicFormat(compressedCiObject.getFormat());
        uploadResult.setPicSize(Long.valueOf(compressedCiObject.getSize()));
        // 设置图片为压缩后的地址
        uploadResult.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        // 设置缩略图地址
        uploadResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
        return uploadResult;
    }
}
